# -*- coding: utf-8 -*-
"""
__author__ = 'Chenshuchuan'
"""
import time
import re
import hashlib


class DataValidator:
	validate_type = None

	def __init__(self):
		self.validate_type = "json"

	def validate(self, data):
		return self.handler(data)

	@staticmethod
	def handler(data):
		if not isinstance(data, dict):
			return False
		return True

	@staticmethod
	def set_default_value(data, key, value):
		"""为可选字段设置默认值(如字段不存在)"""
		if key in data.keys():
			data[key] = value

	@staticmethod
	def set_value(data, key, value):
		"""设置字段值"""
		data[key] = value

	@staticmethod
	def must_has_value(data, keys):
		"""字段不能为空"""
		rv = True
		for key in keys:
			if data[key] in ["", None]:
				rv = False
				break
		return rv

	@staticmethod
	def must_has_key(data, keys):
		"""检测数据中是否包含必须字段"""
		rv = True
		for k in keys:
			if k not in data.iterkeys():
				rv = False
				break
		return rv

	@staticmethod
	def filter_key_value(data):
		"""过滤为空的字段"""
		return dict([(k, v) for k, v in data.items() if v not in ["", None]])


def format_stamp_local_time():
	"""
	时间戳格式化
	:param val:
	:return:
	"""
	return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


def validate_login_user(username):
	email = re.compile('[^\._-][\w\.-]+@(?:[A-Za-z0-9]+\.)+[A-Za-z]')
	tel = re.compile('^0\d{2,3}\d{7,8}$|^1[23589]\d{9}$|^147\d{8}')
	modile = re.compile('^[A-Za-z0-9]')
	id_card = re.compile('^(\d{15}$)|(^\d{17}([0-9]|X|x)$)')
	wechat_openid = re.compile('^[\w\-]{28}$')
	wechat_unionid = re.compile('^[\w\-]{29}$')

	if email.match(username) and len(username) > 7:
		return "email"

	if modile.match(username):
		return "mobile"


def validate_mobile(phone):
	modile = re.compile('^0\d{2,3}\d{7,8}$|^1[23589]\d{9}$|^147\d{8}')
	return True if modile.match(phone) else False


def validate_login_password(user, password):
	if user is None:
		return {"errcode": 404, "errmsg": u"该用户不存在该系统中!"}
	if user is not None and user.verify_password(password):
		return {"errcode": 200, "errmsg": u"ok"}
	else:
		return {"errcode": 404, "errmsg": u"您输入的密码有误!"}


def validation_passwd(password_salt, crypted_password, passwd):
	"""
	密码验证
	:param password_salt: 数据库存储的
	:param crypted_password: 数据库存储的密码
	:param passwd: 输入的密码
	:return:
	"""
	status = False
	a_salt = passwd + password_salt
	for i in range(20):
		a_salt = hashlib.sha512(a_salt).hexdigest()
	if a_salt == crypted_password:
		status = True
	return status
